package com.xgq.drink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgq.drink.entity.MemberLevel;
import com.xgq.drink.mapper.MemberLevelMapper;
import com.xgq.drink.service.IMemberLevelService;
import com.xgq.drink.utils.RedisUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MemberLevelServiceImpl extends ServiceImpl<MemberLevelMapper, MemberLevel> implements IMemberLevelService {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ObjectMapper objectMapper; // 注入 ObjectMapper

    private static final String MEMBER_LEVEL_CACHE_KEY = "member:levels";

    @Override
    public List<MemberLevel> getAllMemberLevels() {
        // 尝试从 Redis 中获取会员层级信息
        String cachedLevels = redisUtil.get(MEMBER_LEVEL_CACHE_KEY);
        if (cachedLevels != null) {
            try {
                // 如果缓存存在，直接返回缓存内容
                return objectMapper.readValue(cachedLevels, new TypeReference<List<MemberLevel>>() {});
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 如果缓存不存在，从数据库中查询
        QueryWrapper<MemberLevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("min_points");
        List<MemberLevel> memberLevels = list(queryWrapper);

        // 将查询结果存入 Redis 缓存，缓存时间设置为 2400 小时
        try {
            redisUtil.set(MEMBER_LEVEL_CACHE_KEY, objectMapper.writeValueAsString(memberLevels), 2400, TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return memberLevels;
    }

    @Override
    public void updateMemberLevel(MemberLevel memberLevel) {
        // 更新数据库中的会员层级信息
        updateById(memberLevel);

        // 清除 Redis 缓存
        redisUtil.set(MEMBER_LEVEL_CACHE_KEY, null, 1, TimeUnit.SECONDS); // 设置一个短暂的过期时间来清除缓存

        // 重新查询并存入新的缓存
        getAllMemberLevels();
    }
}